/**
 * 
 */
package fluo.centralserver;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;

/**
 * @author maherbeg
 *
 * Created: Apr 2, 2009
 * Modified: Apr 2, 2009
 */
public class CentralServer implements CentralServerDetails, Runnable {

	ServerSocket RegisterSocket;
	private HashMap<String, RegisterDesktop> servers;
	private boolean debug = true;
	
	public CentralServer(){
		servers = new HashMap<String, RegisterDesktop>();
		try {
			RegisterSocket = new ServerSocket();
			RegisterSocket.setReuseAddress(true);
			RegisterSocket.bind(new InetSocketAddress(CentralServerDetails.ip, CentralServerDetails.port));
		} catch (IOException e) {
			System.out.println("CentralServer.CentralServer(): Error binding address and creating socket...exiting system.");
			e.printStackTrace();
			System.exit(0);
		}
		
		Thread t = new Thread(this);
		t.start();
	}

	public void run() {
		while(true){
			try {
				if(debug) System.out.println("CentralServer.run(): Waiting for a new connection...");
				
				Socket sock = RegisterSocket.accept();
				
				if(debug) System.out.println("CentralServer.run(): New connection created, spawning new registration thread.");
				
				new RegistrationThread(this, sock);
			} catch (IOException e) {
				System.out.println("CentralServer.run(): Error accepting new connection, please try connecting again.");
				e.printStackTrace();
			}
			
		}
		
	}

	//Returns true if we could add the desktop to our list of clients
	//Returns false if the name already exists
	public boolean registerDesktop(RegisterDesktop desktop) {
		if(debug) System.out.println("CentralServer.registerDesktop(): Registering new desktop " + desktop);
		if(servers.containsKey(desktop.getServerName())){
			return false;
		}
		
		servers.put(desktop.getServerName(), desktop);
		return true;
	}
	
	public static void main(String args[]){
		CentralServer cs = new CentralServer();
		fluo.desktopserver.DesktopServer ds = new fluo.desktopserver.DesktopServer();
	}
}
